package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.TravelComment;
import cn.wolfcode.wolf2w.query.QueryObject;
import cn.wolfcode.wolf2w.repository.TravelCommentRepository;
import cn.wolfcode.wolf2w.service.ITravelCommentService;
import cn.wolfcode.wolf2w.util.DBHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class TravelCommentServiceImpl implements ITravelCommentService {

    @Autowired
    private TravelCommentRepository travelCommentRepository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(TravelComment travelComment) {
        travelComment.setId(null);
        travelCommentRepository.save(travelComment);
    }

    @Override
    public void delete(String id) {
        travelCommentRepository.deleteById(id);
    }

    @Override
    public void update(TravelComment travelComment) {
        travelCommentRepository.save(travelComment);
    }

    @Override
    public TravelComment get(String id) {
        return travelCommentRepository.findById(id).orElse(null);
    }

    @Override
    public Page<TravelComment> query(QueryObject qo) {
        // 创建拼接对象
        Query query = new Query();
        // 使用PageRequest.of,传入当前页 - 1 (记得-1, 因为当前页从0开始), 页面显示条数, 排序规则, 排序的列
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");
        return DBHelper.query(template, qo, query, pageable, TravelComment.class);
    }

    @Override
    public List<TravelComment> findByTravelId(String travelId) {
        return travelCommentRepository.findByTravelId(travelId);
    }

    @Override
    public List<TravelComment> list() {
        return travelCommentRepository.findAll();
    }
}
